package edu.towson.cosc490.incaseofemergency;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import edu.towson.cosc490.incaseofemergency.objects.WeatherItem;
import edu.towson.cosc490.incaseofemergency.parsers.AndroidSaxFeedParser;

public class WeatherNotifications extends ListActivity {

	private List<WeatherItem> items;
	private ListActivity thisContext = this;

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setMessage("Weather Notifications");

		alert.setPositiveButton("Use My Location",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						loadFeed();
					}
				});

		alert.setNegativeButton("Enter Zip Code",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						enterZip();
					}
				});

		alert.show();
		setContentView(R.layout.activity_weather_notifications);
		ListView list = getListView();
		registerForContextMenu(list);
	}

	public void enterZip() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setMessage("Enter Zip Code:");

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		input.setInputType(2);
		alert.setView(input);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String zip = input.getText().toString();
				String feedUrl = "http://rss.weather.com/weather/rss/local/"
						+ zip + "?cm_ven=LWO&cm_cat=rss&par=LWO_rss";
				displayFeed(feedUrl);
			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});

		alert.show();
	}

	private void loadFeed() {
		LinearLayout progLayout = (LinearLayout) findViewById(R.id.progress_layout);
		progLayout.setVisibility(0);
		Log.i("debug", "starting loadFeed");
		final LocationManager locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
		if (locationManager == null)
			Log.i("debug", "locaton manager null");
		if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Log.i("debug", "gps disabled");
			AlertDialog.Builder alert = new AlertDialog.Builder(thisContext);

			alert.setMessage("GPS is disabled.  Please enter zip code manually.");

			alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					enterZip();
				}
			});
			
			alert.show();
		}
		LocationListener locationListener = new MyLocationListener();
		Log.i("debug", "starting locationListener");
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				35000, 10, locationListener);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		/*Intent viewMessage = new Intent(Intent.ACTION_VIEW, Uri.parse(items
				.get(position).getLink().toExternalForm()));
		startActivity(viewMessage);*/
		
		Intent viewLink = new Intent(thisContext, WeatherLink.class);
		viewLink.putExtra("url", items.get(position).getLink().toExternalForm());
		startActivity(viewLink);
	}

	private final class MyLocationListener implements LocationListener {
		private boolean locationFound = false;

		@Override
		public void onLocationChanged(Location locFromGps) {
			// called when the listener is notified with a location update from
			// the GPS
			if (!locationFound) {
				Location location = locFromGps;
				Geocoder geo = new Geocoder(thisContext);
				Log.i("debug", "got geo");
				try {
					Log.i("debug", "Lat: " + location.getLatitude() + " Long: "
							+ location.getLongitude());
					List<Address> addresses = geo.getFromLocation(
							location.getLatitude(), location.getLongitude(), 1);
					if (addresses.get(0) == null)
						Log.i("debug", "address(0) is null");
					Address myAddress = addresses.get(0);
					Log.i("debug", "address: " + myAddress.toString());
					Log.i("debug", "Postal Code : " + myAddress.getPostalCode());
					String zipCode = myAddress.getPostalCode();
					Log.i("debug", "zipCode : " + zipCode);
					if(zipCode == null) {
						AlertDialog.Builder alert = new AlertDialog.Builder(thisContext);

						alert.setMessage("Error determining location.  Please enter zip code manually.");

						alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
								enterZip();
							}
						});
						
						alert.show();
					}
					String feedUrl = "http://rss.weather.com/weather/rss/local/"
							+ zipCode + "?cm_ven=LWO&cm_cat=rss&par=LWO_rss";
					Log.i("debug", "5");
					displayFeed(feedUrl);
				} catch (Throwable t) {
					Log.i("debug", t.toString());
				}

				locationFound = true;
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
			// called when the GPS provider is turned off (user turning off the
			// GPS on the phone)
		}

		@Override
		public void onProviderEnabled(String provider) {
			// called when the GPS provider is turned on (user turning on the
			// GPS on the phone)
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// called when the status of the GPS provider changes
		}
	}

	public void displayFeed(String URL) {
		try {
			LinearLayout progLayout = (LinearLayout) findViewById(R.id.progress_layout);
			progLayout.setVisibility(8);
			AndroidSaxFeedParser parser = new AndroidSaxFeedParser(URL);
			Log.i("debug", "created parser with : " + URL);
			items = parser.parse();
			Log.i("debug", "parser done");
			List<String> titles = new ArrayList<String>(items.size());
			Log.i("debug", "created title list");
			for (WeatherItem rd : items) {
				titles.add(rd.getTitle());
				Log.i("debug", "title : " + rd.getTitle());
			}
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(
					thisContext, R.layout.row_weather_notification, titles);
			thisContext.setListAdapter(adapter);
		} catch (Throwable t) {
			Log.i("debug", t.toString());
		}
	}

}
